package account

import (
	"NovelBook/dao"
	"NovelBook/models/db_models"
	"NovelBook/models/res"
	"errors"
	"log"
)

// Modify 修改昵称或头像，其中一个不修改传原值
func Modify(uid uint, info res.UserAvatar, userType UserType) error {

	var err error
	switch userType {
	case SUPERUSER:
		err = dao.GetDb().Model(&db_models.Superuser{}).Where("id = ?", uid).
			Updates(map[string]interface{}{"username": info.Username, "avatar": info.Avatar}).Error
	case MANAGER:
		err = dao.GetDb().Model(&db_models.Manager{}).Where("id = ?", uid).
			Updates(map[string]interface{}{"username": info.Username, "avatar": info.Avatar}).Error
	case WORKER:
		err = dao.GetDb().Model(&db_models.Worker{}).Where("id = ?", uid).
			Updates(map[string]interface{}{"username": info.Username, "avatar": info.Avatar}).Error
	case BORROWER:
		err = dao.GetDb().Model(&db_models.Borrower{}).Where("id = ?", uid).
			Updates(map[string]interface{}{"username": info.Username, "avatar": info.Avatar}).Error
	}

	return err
}

// ResetPassword 重置密码
func ResetPassword(resetInfo res.ResetInfo, userType UserType) error {
	// 处理验证码
	// 从Redis获取 <email, captcha>
	// 对比：Info.Captcha 与 Redis中的
	captcha, err := GetCaptcha(resetInfo.Email)
	if err != nil {
		log.Println("redis error:", err)
		return err
	}
	if captcha != resetInfo.Captcha || err != nil {
		return errors.New("captcha error")
	}

	switch userType {
	case SUPERUSER:
		err = dao.GetDb().Model(db_models.Superuser{}).Where("email = ?", resetInfo.Email).
			Updates(map[string]interface{}{"password": resetInfo.Password}).Error
	case MANAGER:
		err = dao.GetDb().Model(db_models.Manager{}).Where("email = ?", resetInfo.Email).
			Updates(map[string]interface{}{"password": resetInfo.Password}).Error
	case WORKER:
		err = dao.GetDb().Model(db_models.Worker{}).Where("email = ?", resetInfo.Email).
			Updates(map[string]interface{}{"password": resetInfo.Password}).Error
	case BORROWER:
		err = dao.GetDb().Model(db_models.Borrower{}).Where("email = ?", resetInfo.Email).
			Updates(map[string]interface{}{"password": resetInfo.Password}).Error
	}

	return err
}
